package com.haiyou.data.game.role;

import java.util.function.Function;

import org.redisson.api.RAtomicLong;

import com.haiyou.common.entity.Prefix;
import com.haiyou.common.system.Properties;
import com.haiyou.data.common.accessor.annotation.BucketAccessorType;
import com.haiyou.data.common.accessor.annotation.CachedPolicy;
import com.haiyou.data.common.accessor.annotation.ExpiryPolicy;
import com.haiyou.data.common.cache.redis.RKeys;
import com.haiyou.data.common.cache.redis.key.RedisPrefix;
import com.haiyou.data.game.base.BucketPlayerAccessor;

@Prefix(RedisPrefix.player)
@CachedPolicy(accessorType = @BucketAccessorType(value = BucketAccessorType.CAFFEINE_REDIS_ACCESSOR))
public class PlayerTableAccessor extends BucketPlayerAccessor<PlayerTable> {

	private String playerIdKeyPrefix;

	@Override
	public void init() {
		super.init();
		playerIdKeyPrefix = getKeyPrefix() + "_playerId";
	}

	/**
	 * uid 生成器
	 * 
	 * @return
	 */
	public RAtomicLong uidCreator() {
		RAtomicLong atomicLong = getRedissonClient()
				.getAtomicLong(RKeys.createRKey(RAtomicLong.class, playerIdKeyPrefix, "keyGenerator"));
		if (atomicLong.get() == 0L) {
			// 账号系统 playerId 起始位置
			// long begin = getKeyPersist(uidKeyPrefix, uidBeginNumberId());
			long begin = playerIdBeginNumberId();
			atomicLong.compareAndSet(0L, begin == 0L ? 0 : begin);
		}

		return atomicLong;
	}

	/**
	 * playerId 生成起始配置
	 * 
	 * @return
	 */
	public long playerIdBeginNumberId() {
		return Properties.player_id_begin_number_id();
	}

	/**
	 * 生成下一个Uid
	 * 
	 * @return
	 */
	public long playerIdNext() {
		return uidCreator().incrementAndGet();
	}

	@Override
	public void destory() {
		super.destory();
		// persistKeyValue(uidKeyPrefix, uidCreator().get());
	}

//	@Override
//	public PlayerTable get(Object key) {
//		return super.get(key);
//	}

	@Override
	public PlayerTable get(String key, Function<? super String, ? extends PlayerTable> mappingFunction) {
		return super.get(key, mappingFunction);
	}

	public void setNextPlayerId(long l) {
		uidCreator().set(l);
	}
}
